// history模式
import {
    createRouter,
    createWebHistory,
} from 'vue-router'

import LoginPage from '../page/LoginPage.vue'
import LayoutPage from "../page/LayoutPage.vue";

const routes = [
// 路由的默认路径
    {
        path: '/',
        redirect: "/main"
    },
    {
        path: '/login',
        name: 'Login',
        component: LoginPage,
        meta: {
            title: '登录'
        }
    },
    {
        path: '/main',
        name: 'Main',
        component: LayoutPage,
        meta:{
            title:'首页'
        }
    }
]

// 创建路由对象
const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    let user_token = localStorage.getItem('token')
    // 未登录
    if (user_token === '' || user_token == null) {
        if (to.path === '/login') {
            next()
        } else {
            next('/login')
        }
    } else {
        if (to.path === '/login') {
            return next('/main')
        } else {
            next()
        }
    }
})

router.afterEach((to) => {
    document.title = to.meta.title
})

export default router;
